import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Button, Row, Col, Form, Input } from 'antd';
import { pwdExp } from '../../utils/regExp';

const FormItem = Form.Item;
const formItemLayout = {
	labelCol: {
		span: 6,
	},
	wrapperCol: {
		span: 14,
	},
};

class Password extends Component {

	onOk = () => {
		// 校验密码
		const { form, onOk } = this.props;
		const { validateFields, setFields } = form;
		validateFields((errors, values) => {
			if (errors) return;
			if (values.newPassword !== values.repeat) {
				return setFields({
					repeat: {
						value: values.repeat,
						errors: [new Error('两次密码不相同')],
					}
				});
			}
			onOk(values);
		});
	}

	onCancel = () => {
		const { handleCancel, form: { setFields } } = this.props;
		setFields({
			oldPassword: { value: '', errors: null },
			repeat: { value: '', errors: null },
			newPassword: { value: '', errors: null }
		});
		handleCancel();
	}

	validator = (rule, value, callback) => {
		const data = this.props.form.getFieldsValue();
		data.newPassword === value ? callback() : callback(true);
	}

	render() {
		const { form, visible } = this.props;
		const { getFieldDecorator } = form;
		return (
			<Modal
				title="重置密码"
				visible={visible}
				onOk={this.onOk}
				onCancel={this.onCancel}
			>
				<Form layout="horizontal">
					<FormItem label="原密码" hasFeedback {...formItemLayout}>
						{getFieldDecorator('oldPassword', {
							rules: [{
								required: true,
								message: '请输入原密码!',
							}]
						})(<Input type="password" />)}
					</FormItem>
					<FormItem label="新密码" hasFeedback {...formItemLayout}>
						{getFieldDecorator('newPassword', {
							rules: [
								{
									required: true,
									message: '请输入新密码!',
								},
								{
									pattern: pwdExp.exp,
									message: pwdExp.des
								}
							]
						})(<Input type="password" />)}
					</FormItem>
					<FormItem label="再次输入新密码" hasFeedback {...formItemLayout}>
						{getFieldDecorator('repeat', {
							rules: [
								{
									required: true,
									message: '请再次输入新密码!'
								},
								{
									validator: this.validator,
									message: '两次密码不相同'
								}
							]
						})(<Input type="password" />)}
					</FormItem>
				</Form>
			</Modal>
		);
	}
}

Password.propTypes = {

};

export default Form.create()(Password);
